﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntityFrameworkETL.SaveBatchedChanges
{
    public interface ICommandParser
    {
        string ParseTableName(DbCommand dbCommand);
        Dictionary<string, bool> ParseFkParameters(DbCommand dbCommand);
    }

    public class CommandParser : ICommandParser
    {
        public string ParseTableName(DbCommand dbCommand)
        {
            var tableName = "";
            int iStart = dbCommand.CommandText.IndexOf(" ", System.StringComparison.Ordinal);
            int iEnd = dbCommand.CommandText.IndexOf("(", System.StringComparison.Ordinal);
            tableName = dbCommand.CommandText.Substring(iStart, iEnd - iStart).Trim();
            tableName = tableName.Replace("[", "");
            return tableName.Replace("]", "");
        }

        public Dictionary<string, bool> ParseFkParameters(DbCommand dbCommand)
        {
            var result = new Dictionary<string, bool>();
            var sql = dbCommand.CommandText;
            var firstline = sql.Substring(0, sql.IndexOf(Environment.NewLine));
            var istart = firstline.IndexOf("](");
            var columnText = firstline.Substring(istart + 2, firstline.Length - istart - 3);
            var columns = new List<string>();
            foreach (var column in columnText.Split(','))
            {
                columns.Add(column.Replace("]", "").Replace("[", ""));
            }
            if (dbCommand.Parameters.Count != columns.Count)
                throw new Exception("ParseFKParameters parsed a different number of columsn than parameters");

            foreach (DbParameter parameter in dbCommand.Parameters)
            {
                var column = columns.First();
                if (column.EndsWith("Id"))
                    result.Add(parameter.ParameterName, true);
                else
                    result.Add(parameter.ParameterName, false);

                columns.Remove(column);
            }
            return result;
        }
   
    }
}
